package com.jt.www.admin.caseinfo.service.impl;

import com.jt.www.admin.caseinfo.service.CaseInfoService;
import com.jt.www.biz.order_pc.service.EndorseService;
import com.jt.www.dao.mapper.endorse.EndorseMapper;
import com.jt.www.domain.dto.JtBranch;
import com.jt.www.domain.qo.EbaoPolicyQO;
import com.jt.www.domain.vo.EbaoPolicyVO;
import com.jt.www.enums.remote.ChannelEnum;
import com.jt.www.model.entity.endorse.EndorseEntity;
import com.jt.www.model.registerCustomer.vo.JtBranchInfoVo;
import com.jt.www.model.registerCustomer.vo.UserManagerResultVo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.remote.EbaoClient;
import com.jt.www.remote.UserClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.*;

@Service
public class CaseInfoServiceImpl implements CaseInfoService {

    public static final Logger log = LoggerFactory.getLogger(CaseInfoServiceImpl.class);

    @Autowired
    private UserClient userClient;

    @Autowired
    private EbaoClient ebaoClient;

    @Autowired
    private InsClient insClient;

    @Autowired
    private EndorseMapper endorseMapper;

    @Autowired
    private EndorseService endorseService;

    @Override
    public ResponseEntity queryAuditors(String findCode, String branchCode, String roleCode, Boolean isRecursion) {

        try {
            GenericListResponse<UserManagerResultVo> resp = userClient.selectChannelManager(branchCode, roleCode,null,null,null,null);

            if("0000".equals(resp.getCode())){
                if(resp.getList() != null && resp.getList().size() > 0){
                    return GenericListResponse.listAndCount(resp.getList(), resp.getList().size());
                }else{
                    // 递归查询上级审核人员
                    if(isRecursion){
                        // 查询上级分支机构
                        GenericDataResponse<JtBranchInfoVo> branchInfo = userClient.querySuperiorBranch(branchCode);

                        if("0000".equals(branchInfo.getCode())){
                            List<UserManagerResultVo> resultList = new ArrayList<>();

                            int num = Integer.valueOf(branchInfo.getData().getBranchLevel());
                            branchCode = branchInfo.getData().getCode();
                            for(int i = 0; i < num; i++){

                                if(i > 0){
                                    branchInfo = userClient.querySuperiorBranch(branchCode);
                                    if("0000".equals(branchInfo.getCode())) {
                                        branchCode = branchInfo.getData().getCode();

                                        if("JT".equals(branchCode)){
                                            branchCode = "JT0000";
                                        }
                                    }
                                }
                                log.info("递归查询上级审核人员 branchCode->{},roleCode->{}",branchCode,roleCode);
                                resp = userClient.selectChannelManager(branchCode,roleCode,null,null,null,null);
                                if("0000".equals(resp.getCode())){
                                    if(resp.getList() != null && resp.getList().size() > 0){
                                        resultList = resp.getList();
                                        break;
                                    }
                                }
                            }
                            return GenericListResponse.listAndCount(resultList, resultList.size());
                        }else{
                            return GenericListResponse.ng("查询上级分支机构异常，稍候重试！");
                        }

                    }else{
                        return GenericListResponse.listNoCount(null);
                    }
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }

        return GenericListResponse.ng("查询服务人员/审核人员异常，稍候重试！");
    }

    @Override
    public ResponseEntity queryThirdGradeBranch(String findCode, String branchCode, String branchName) {

        try {
            if("JT0000".equals(branchCode)){
                GenericListResponse<JtBranch> response = userClient.getJtBranchByChannel(ChannelEnum.EDU.getChannelCode());
                if(GenericListResponse.CODE_OK.equals(response.getCode()) && CollectionUtils.isNotEmpty(response.getList())){
                    JtBranch vo = new JtBranch();
                    vo.setCode(branchCode);
                    vo.setJtBranchName(branchName);
                    response.getList().add(vo);
                    return GenericListResponse.listAndCount(response.getList(),response.getList().size());
                }
            }else {
                GenericListResponse<JtBranchInfoVo> branchs = userClient.queryThirdGradeBranch(branchCode);
                if(branchs.getList() != null && branchs.getList().size() > 0){
                    JtBranchInfoVo vo = new JtBranchInfoVo();
                    vo.setCode(branchCode);
                    vo.setJtBranchName(branchName);
                    branchs.getList().add(vo);
                    return GenericListResponse.listAndCount(branchs.getList(),branchs.getList().size());
                }
            }
            List<JtBranchInfoVo> list = new ArrayList<>();
            JtBranchInfoVo vo = new JtBranchInfoVo();
            vo.setCode(branchCode);
            vo.setJtBranchName(branchName);
            list.add(vo);
            return GenericListResponse.listAndCount(list,list.size());
        } catch(Exception e){
            e.printStackTrace();
            return GenericListResponse.ng("查询服务人员/审核人员异常，稍候重试！");
        }
    }

    @Override
    public ResponseEntity<GenericListResponse<EbaoPolicyVO>> ebaoPolicyList(String findCode, EbaoPolicyQO ebaoPolicyQO) {
        try{

            log.info("{} 查询ebao保单列表 service 开始 ", findCode);
            GenericListResponse<EbaoPolicyVO> responseEntity = ebaoClient.ebaoPolicyList(ebaoPolicyQO.getPn(),ebaoPolicyQO.getPs(),
                    ebaoPolicyQO.getBusType1Code(),ebaoPolicyQO.getBusType2Code(),ebaoPolicyQO.getBusType3Code(),
                    ebaoPolicyQO.getPolicyNo(),ebaoPolicyQO.getRiskName(),ebaoPolicyQO.getCustomerName(),
                    ebaoPolicyQO.getIdCard(),ebaoPolicyQO.getProvinceCode(),ebaoPolicyQO.getCityCode() ,
                    ebaoPolicyQO.getAreaCode(),ebaoPolicyQO.getApplicant(),ebaoPolicyQO.getInsured(),
                    ebaoPolicyQO.getShipName(),ebaoPolicyQO.getLicenseNo(),ebaoPolicyQO.getBranchCode(),
                    ebaoPolicyQO.getPolicyStartDate1(),ebaoPolicyQO.getPolicyStartDate2(),ebaoPolicyQO.getPolicyEndDate1(),
                    ebaoPolicyQO.getPolicyEndDate2(),ebaoPolicyQO.getFilterCar());

            log.info("{} 查询ebao保单列表 service 调用ebao接口返回结果 result->{} ", findCode,JsonUtil.object2Json(responseEntity));

            if(responseEntity != null){

                return GenericListResponse.listAndCount(responseEntity.getList(),responseEntity.getTotal());
            }
            return GenericListResponse.listAndCount(null,0L);
        }catch (Exception e){
            e.printStackTrace();
            log.info("{} 查询ebao保单列表 service 调用ebao接口异常 e->{}", e);
            return GenericListResponse.listAndCount(null,0L);
        }
    }

    @Override
    public ResponseEntity isInclude(String insuranceId, String licenceNos) {

        String findCode = "isInclude_" + System.currentTimeMillis();

        log.info("{} 判断出险人是否在清单内 投保单号：{}, 出险人证件号码：{}", findCode, insuranceId, licenceNos);

        endorseService.analysisEndorse(insuranceId);

        Map<String,Boolean> result = new HashMap<>();
        String[] licenceNoList = licenceNos.split(",");
        for(String licenceNo : licenceNoList){

            List<String> statusList = Arrays.asList("I","R");
            Weekend<EndorseEntity> endorseWeekend = new Weekend<>(EndorseEntity.class);
            WeekendCriteria<EndorseEntity, Object> endorseCriteria = endorseWeekend.weekendCriteria();

            endorseCriteria.andEqualTo(EndorseEntity::getInsuranceId, insuranceId);
            endorseCriteria.andEqualTo(EndorseEntity::getCardno, licenceNo);
            endorseCriteria.andIn(EndorseEntity::getStatus, statusList);

            List<EndorseEntity> endorseList = endorseMapper.selectByExample(endorseWeekend);

            if(endorseList != null && endorseList.size() > 0){
                result.put(licenceNo,true);
                log.info("{} 判断出险人是否在清单内 投保单号：{}, 出险人证件号码：{}，是否在清单内->true", findCode, insuranceId, licenceNos);
            }else {
                result.put(licenceNo,false);
                log.info("{} 判断出险人是否在清单内 投保单号：{}, 出险人证件号码：{}，是否在清单内->false", findCode, insuranceId, licenceNos);
            }
        }
        return GenericDataResponse.okWithData(result);
    }
}
